matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


var spiralOrder = function (matrix) {
    let m = matrix.length, n = matrix[0].length
    let result = []
    let top = 0, bottom = m - 1, left = 0, right = n - 1

    while (top <= bottom && left <= right) {
        for (let j = left; j <= right; j++) {
            result.push(matrix[top][j])
        }
        top++
        if (top > bottom) break;

        for (let i = top; i <= bottom; i++) {
            result.push(matrix[i][right])
        }
        right--
        if (left > right) break;

        for (let j = right; j >= left; j--) {
            result.push(matrix[bottom][j])
        }
        bottom--
        if (top > bottom) break;

        for (let i = bottom; i >= top; i--) {
            result.push(matrix[i][left])
        }
        left++
    }
    return result;
};

console.log(spiralOrder(matrix));
